import { ref } from 'vue'
import { RESUME_THEME } from '@/constant/localStore'

import type { ThemeNameType, Mode } from '@/types/Theme'
import type { Ref } from 'vue'

let useTheme: Ref<ThemeNameType> = ref('system')
let isInit: Ref<Boolean> = ref(true)

/**
 * @description 监听用户系统主题切换
 */
function watchUserSystem() {
  if (useTheme.value !== 'system') return
  const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  darkModeMediaQuery.onchange = () => useChangeTheme('system')
}

/**
 * @description 初始化主题
 */
function useInitTheme() {
  if (localStorage.getItem(RESUME_THEME)) {
    useTheme.value = localStorage.getItem(RESUME_THEME) as ThemeNameType
    useChangeTheme(useTheme.value)
  } else {
    useChangeTheme('system')
  }
  watchUserSystem()
  isInit.value = false
}

function useChangeTheme(themeName: ThemeNameType | never) {
  localStorage.setItem(RESUME_THEME, themeName)

  switch (themeName) {
    case 'system':
      if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        transition('dark')
        useTheme.value = 'dark'
      } else {
        transition('light')
        useTheme.value = 'light'
      }
      break
    case 'light':
      transition('light')
      useTheme.value = 'light'
      break
    case 'dark':
      transition('dark')
      useTheme.value = 'dark'
      break

    default:
      const _: never = themeName
      break
  }
}

function transition(mode: Mode) {
  function _setHtmlAttr() {
    if (mode === 'dark') {
      document.documentElement.setAttribute('data-theme', 'dark')
    } else {
      document.documentElement.removeAttribute('data-theme')
    }
  }
  if (document.startViewTransition && !isInit.value) {
    document.startViewTransition(function () {
      _setHtmlAttr()
    })
  } else {
    _setHtmlAttr()
  }
}

export { useTheme, useInitTheme, useChangeTheme }
